// 设置默认信息
$.validator.setDefaults({
    submitHandler: function (val) {
        //submit('',successcallback('修改成功,请重新登陆',$('.formsub').attr('tipurl')));
    },
    groups: {
        date: "year month day"
    },
    errorPlacement: function (error, element) {
        element.parents('td').append(error);
    }
});

$(document).ready(function () {
    // 限制只能输入数字
    var record;
    $("#year,#month,#day").on('keyup', function () {
        var myThis = $(this);
        var val = myThis.val();
        var decimalReg = /^[1-9][0-9]*$/;
        if (val != '' && decimalReg.test(val)) {
            record = val;
        } else {
            if (val != '') {
                myThis.val(record);
            }
        }
        myThis.blur(function () {
            record = '';
        });
    });

 $("#money").on('keyup', function () {
        var myThis = $(this);
        var val = myThis.val();
        var decimalReg = /^\d{0,999}\.{0,1}(\d{1,999})?$/;
        if (val != '' && decimalReg.test(val)) {
            record = val;
        } else {
            if (val != '') {
                myThis.val(record);
            }
        }
        myThis.blur(function () {
            record = '';
        });
    });
    
    $(".table_box input[type=text]").focus(function () {
        $(this).addClass('u-ipt-active');
        $(this).removeClass('error');
        $(this).next('label.error').hide();
    });


    $(".table_box input[type=text]").blur(function () {
        $(this).removeClass('u-ipt-active');
        if ($(this).parent().find('label.error').is(":visible")) {
            $(this).addClass('error');
        } else {
            $(this).removeClass('error');
            $(this).removeClass('u-ipt-active');
        }
    });


    // 上传文件
    var
    $list = $('#thelist'),
    // $btn = $('#ctlBtn'),
    state = 'pending',
    fileCount = 0,
    uploader;
    var uploader = WebUploader.create({
        // swf文件路径
        swf: 'Uploader.swf',

        // 文件接收服务端。
        server: $('#uploadcontract').val(),

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#picker',
        chunked: true,
        chunkSize: 2 * 1024 * 1024,
        accept: {
            title: 'PDF文件',
            extensions: 'pdf',
            mimeTypes: '.pdf'
        }
    });

    uploader.addFile = function (file) {
        var $li = $(
                '<div id="' + file.id + '" class="item fn-clear">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<i class="delete"></i>' +
                '</div>');
       if( $("#thelist a").length>0){
           $("#thelist a").each(function(){
            if($(this).text()!==file.name){
                  $li.appendTo($list);
            }
         }); 
       }else{
            $li.appendTo($list);
       }
      
        filename = file.name;
        file.orgname=filename;
        var index1 = filename.lastIndexOf(".");
        var index2 = filename.length;
        var ext = filename.substring(index1, index2);//后缀名
        file.name = WebUploader.guid() + ext;
        
        $li.on('click', '.delete', function () {
            uploader.removeFile(file, true);
        });
    };
    
    $(".delete").click(function(){
        $(this).parents('.item').remove();
    })

    uploader.onFileQueued = function (file) {
        fileCount++;
        uploader.addFile(file);
    };

    uploader.onFileDequeued = function (file) {
        fileCount--;
        removeFile(file);
    };

    $list.on('mouseenter mouseleave', '.item', function () {
        $(this).toggleClass("hover");
    });

    //删除文件
    function removeFile(file) {
        var $li = $('#' + file.id);
        $li.remove();
    }
//
//    uploader.on('uploadError', function (file) {
//        var $li = $('#' + file.id),
//                $error = $li.find('div.error');
//        // 避免重复创建
//        if (!$error.length) {
//            $error = $('<div class="error"></div>').appendTo($li);
//        }
//
//        $error.text('上传失败');
//
//    });

    $('#picker').change(function () {
        // $(this).parents('td').find("label.error").hide();
        if ($("#thelist .item").length > 0) {
            $(this).parents('td').find("label.error").hide();
        }
    })


    uploader.on('uploadSuccess', function (file, response) {
        // $("#account_form").submit();
        if (response.error.code == '0')
        {
           $('#'+file.id).append("<input name='filepath[]'type='hidden' class='num_path ' value='" + response.result.showpath + "'/>");
           $('#'+file.id).append("<input name='filename[]'type='hidden' value='" + file.orgname + "'/>");
        } 
        else
        {
            layer.alert('文件上传失败，请重新上传', {
                icon: 2,
                btn: false,
                closeBtn: 0,
                time: 2000
            });

            $('#'+file.id).find("h4").css("color","red");
        }
    });
    uploader.on('uploadFinished', function (  ) {
        if ($(".num_path").length == $("#thelist .item").length) {
            oktipsoption = {
                type: 1,
                url: $('.formsub').attr('url'),
                msg: '提交成功'
            };
            ajaxform.init(oktipsoption, '.formsub');
            ajaxform.submit();
        }
    });



    uploader.on('uploadError', function (file) {
        layer.alert('文件上传失败,请重新上传', {
            icon: 2,
            btn: false,
            closeBtn: 0,
            time: 2000
        });
        $("#"+file.id).find("h4").css("color","red");
    });

    $("#upload_btn").click(function () {
        if (account_form.form()) {
            if($(".num_path").length == $("#thelist .item").length){
                 oktipsoption = {
                    type: 1,
                    url: $('.formsub').attr('url'),
                    msg: '提交成功'
                };
                ajaxform.init(oktipsoption, '.formsub');
                ajaxform.submit();
            }else{
                  uploader.upload();
            }
           
        }
    })


    var account_form = $("#account_form").validate({
        rules: {
            file: {
                required: {
                    depends: function () { //三选一  
                        return ($("#thelist .item").length <= 0);
                    }
                }
            },
            year: {
                required: {
                    depends: function () { //三选一  
                        return ($("#month").val().length <= 0 && $("#day").val().length <= 0);
                    }
                }
            },
            month: {
                required: {
                    depends: function () { //三选一  
                        return ($("#year").val().length <= 0 && $("#day").val().length <= 0);
                    }
                }
            },
            day: {
                required: {
                    depends: function () { //三选一  
                        return ($("#month").val().length <= 0 && $("#year").val().length <= 0);
                    }
                }
            },
            money: {
                required: true
            },
            get_info:{
            required:true
           }
        },
        messages: {
            file: {
                required: '请上传合同'
            },
            year: {
                required: '请填写账期'
            },
            month: {
                required: '请填写账期'
            },
            day: {
                required: '请填写账期'
            },
            money: {
                required: '请填写合同应付总额'
            },
             get_info:{
            required:'请填写补充材料'
           }
        },
        focusInvalid: false,
        onkeyup: false
    });
})